package com.code.ape.codeape.common.security.component;

import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author 公众号：码猿技术专栏
 * @url: www.java-family.cn
 * @description 主、子线程的数据传输
 */
public class ContextTaskDecorator implements TaskDecorator {
	@Override
	public Runnable decorate(Runnable runnable) {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return () -> {
			try {
				RequestContextHolder.setRequestAttributes(attributes);
				// 执行子线程，这一步不要忘了
				runnable.run();
			} finally {
				// 线程结束，清空这些信息，否则可能造成内存泄漏
				RequestContextHolder.resetRequestAttributes();
			}
		};
	}
}
